import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [

  {
    path: '/',
    name: 'login',
    component: () => import('../views/LoginIndex.vue')
  },
  {
    path: '/index',
    name: 'index',
    component: () => import('../views/IndexView.vue'),
    redirect: "/index/users",
    children: [
      {
        path: 'users',
        name: 'users',
        component: () => import('../views/UsersView.vue'),
        meta: {
          title: '用户管理',
          subTitle:"用户列表"
        },
      }, {
        path: 'addusers',
        name: 'addusers',
        component: () => import('../views/AddusersView.vue'),
        meta: {
          title: '用户管理',
          subTitle:"添加用户",
          // true表示用户列表组件需要被缓存,false表示用户列表组件不需要被缓存
          keepAlive:true
        },
      },
    ]
  }, {
    path: '/register',
    name: 'register',
    component: () => import('../views/RegisterView.vue')
  }
]
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}
const router = new VueRouter({
  routes
})

// 全局路由守卫
router.beforeEach((to,from,next)=>{
  // 如果去的不是登录页并且本地缓存中没有token，那么就强制跳转到登录页，让用户去登录
  if(to.name !=='login' && !localStorage.token) next({name:'login'})
  else next()
})
export default router
